package com.sysu.ooad.dao.impl;

import java.util.List;

import org.springframework.stereotype.Component;

import com.sysu.ooad.dao.CommonDao;
import com.sysu.ooad.dao.HomeworkDao;
import com.sysu.ooad.entity.Group;
import com.sysu.ooad.entity.Homework;
import com.sysu.ooad.entity.Student;
import com.sysu.ooad.entity.Task;

@Component("homeworkDao")
public class HomeworkDaoImpl extends CommonDao implements HomeworkDao{

	public void add(Homework homework) {
		hibernateTemplate.save(homework);
	}

	@SuppressWarnings("unchecked")
	public Homework findByTaskAndStudent(Student student, Task task) {
		List<Homework> list = (List<Homework>)hibernateTemplate.find("from Homework h where h.student = ? and h.task = ?", 
				new Object[]{student, task});
		if(list.isEmpty()) return null;
		return list.get(0);
	}

	public void update(Homework homework) {
		hibernateTemplate.update(homework);
	}

	@SuppressWarnings("unchecked")
	public List<Homework> findByGroup(Group group) {
		List<Homework> homeworks = (List<Homework>)hibernateTemplate.find("from Homework h where h.student.group = ?", new Object[]{group});
		return homeworks;
	}

	@SuppressWarnings("unchecked")
	public List<Homework> findByStudent(Student s) {
		return (List<Homework>)hibernateTemplate.find("select h from Homework h where h.student = ? order by h.time desc", new Object[]{s});
	}

	@SuppressWarnings("unchecked")
	public List<Homework> findByTaskAndGroup(Task task, Group group) {
		return (List<Homework>)hibernateTemplate.find("select h from Homework as h where h.task = ? and h.student.group = ?", 
				new Object[]{task, group});
	}

	public Homework findById(Integer id) {
		return (Homework) hibernateTemplate.get(Homework.class, id);
	}
}
